package ops.view.forms.component;

import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JComboBox;
import javax.swing.JComponent;

import ops.view.forms.NonClearableInput;

public class ComboboxInput extends FormInput implements NonClearableInput {

	private JComboBox comboBox;
	
	private Map<String, Object> textToCode;
	
	public ComboboxInput(String label, boolean required, Map<String, Object> map) {
		super(label, required);
		
		comboBox = new JComboBox();
		
		updateData(map);
	}

	public void updateData(Map<String, Object> map) {
		clearInput();
		
		textToCode = new HashMap<String, Object>(map);
		
		for (String s : textToCode.keySet()) {
			comboBox.addItem(s);
		}
	}
	
	public void addActionListener(ActionListener listener) {
		comboBox.addActionListener(listener);
	}
	
	@Override
	public void clearInput() {
		comboBox.removeAllItems();
	}

	@Override
	public JComponent getInputComponent() {
		return comboBox;
	}

	@Override
	public Object getInputValue() {
		String selected = comboBox.getSelectedItem().toString();
		
		Object ret = textToCode.get(selected);
		
		if (ret instanceof Number) {
			return ((Number) ret).doubleValue();
		} else {
			return ret;
		}
	}

	@Override
	public void setInputValue(Object value) {
		comboBox.setSelectedItem(value);
	}

}
